package com.lenovo.smarttraffic.zjh;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.ui.activity.BaseActivity;
import com.lenovo.smarttraffic.zjh.Bean.Bran_Traffic;
import com.lenovo.smarttraffic.zjh.Bean_Json.Bean_JsonTraffic;
import com.lenovo.smarttraffic.zjh.api.Interface_TrafficOnTime;
import com.lenovo.smarttraffic.zm.Map.MyMapActivivty;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.lenovo.smarttraffic.zjh.Setting_Activity.URL_My;

public class _zjh_Activity_TrafficOnTime extends BaseActivity {
    private TextView tvMap;
    private EditText editNumber;
    private TextView tvSearch;
    private ListView lvSearchHistory;
    private TextView tvClear;
    SharedPreferences sp;
    SharedPreferences.Editor editor;
    private List<SearchHistory> list_his = new ArrayList<>();
    Adapter_SearchHistory adapter_searchHistory;
    public static List<TrafficInfo> list_Info = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initToolBar("实时交通");
        initView();
        initData();

    }

    private void initData() {
        sp = getSharedPreferences("Search", MODE_PRIVATE);
        editor = sp.edit();
        String json = sp.getString("Search", null);
        if (json != null) {
            Type type = new TypeToken<List<SearchHistory>>() {
            }.getType();
            list_his = new Gson().fromJson(json, type);
        }
        adapter_searchHistory = new Adapter_SearchHistory();
        lvSearchHistory.setAdapter(adapter_searchHistory);

    }

    private void initView() {
        tvMap = (TextView) findViewById(R.id.tv_Map);
        editNumber = (EditText) findViewById(R.id.edit_Number);
        tvSearch = (TextView) findViewById(R.id.tv_Search);
        lvSearchHistory = (ListView) findViewById(R.id.lv_SearchHistory);
        tvClear = (TextView) findViewById(R.id.tv_Clear);

        tvMap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(_zjh_Activity_TrafficOnTime.this, MyMapActivivty.class));
            }
        });

        tvClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                list_his.clear();
                editor.clear().commit();
//                editor.putString("Search",new Gson().toJson(list_his)).commit();
                adapter_searchHistory.notifyDataSetChanged();
            }
        });

        editNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 0) {

                } else {
                    if (Integer.parseInt(editNumber.getText().toString())>8||Integer.parseInt(editNumber.getText().toString())<1){
                        s="";
                        editNumber.setText(s);
                        Toast.makeText(_zjh_Activity_TrafficOnTime.this, "无该路车！", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        tvSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!editNumber.getText().toString().isEmpty()) {
                    Retrofit retrofit = new Retrofit.Builder()
                            .baseUrl(URL_My)
                            .addConverterFactory(GsonConverterFactory.create())
                            .build();
                    Interface_TrafficOnTime request = retrofit.create(Interface_TrafficOnTime.class);
                    Call<Bran_Traffic> call = request.getCall(new Bean_JsonTraffic(Integer.parseInt(editNumber.getText().toString()), "user1"));
                    call.enqueue(new Callback<Bran_Traffic>() {
                        @Override
                        public void onResponse(Call<Bran_Traffic> call, Response<Bran_Traffic> response) {
                            if (response.code() == 200) {
                                Bran_Traffic.ROWSDETAILBean rowsdetailBean = response.body().getROWS_DETAIL().get(0);
                                list_his.add(new SearchHistory(Integer.parseInt(editNumber.getText().toString()), "(" + rowsdetailBean.getTransfersites().get(0) + "-" + rowsdetailBean.getTransfersites().get(1) + ")"));
                                editor.putString("Search", new Gson().toJson(list_his)).commit();
                                adapter_searchHistory.notifyDataSetChanged();
                                list_Info.clear();
                                list_Info.add(new TrafficInfo(Integer.parseInt(editNumber.getText().toString()), rowsdetailBean.getTransfersites(),
                                        rowsdetailBean.getTime().get(0).getStarttime(), rowsdetailBean.getTime().get(0).getEndtime(),
                                        rowsdetailBean.getSites()));
                                startActivity(new Intent(_zjh_Activity_TrafficOnTime.this, _zjh_Activity_TrafficInfo.class));
                            } else {
                                Toast.makeText(_zjh_Activity_TrafficOnTime.this, "请求失败！", Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onFailure(Call<Bran_Traffic> call, Throwable t) {
                            Toast.makeText(_zjh_Activity_TrafficOnTime.this, "请求失败！", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });

    }

    private class Adapter_SearchHistory extends BaseAdapter {
        private TextView tvHisItem;

        @Override
        public int getCount() {
            return list_his.size();
        }

        @Override
        public Object getItem(int position) {
            return list_his.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = LayoutInflater.from(_zjh_Activity_TrafficOnTime.this).inflate(R.layout._zjh_layout_searchhisitem, parent, false);
            tvHisItem = (TextView) convertView.findViewById(R.id.tv_hisItem);
            tvHisItem.setText(list_his.get(position).getId() + list_his.get(position).getTransferStation());

            return convertView;
        }
    }

    public class TrafficInfo {
        int Line_Id;
        List<String> list_transfer;

        public TrafficInfo(int line_Id, List<String> list_transfer, String startTime, String endTime, List<String> list_line) {
            Line_Id = line_Id;
            this.list_transfer = list_transfer;
            this.startTime = startTime;
            this.endTime = endTime;
            this.list_line = list_line;
        }

        public int getLine_Id() {
            return Line_Id;
        }

        public void setLine_Id(int line_Id) {
            Line_Id = line_Id;
        }

        public List<String> getList_transfer() {
            return list_transfer;
        }

        public void setList_transfer(List<String> list_transfer) {
            this.list_transfer = list_transfer;
        }

        public String getStartTime() {
            return startTime;
        }

        public void setStartTime(String startTime) {
            this.startTime = startTime;
        }

        public String getEndTime() {
            return endTime;
        }

        public void setEndTime(String endTime) {
            this.endTime = endTime;
        }

        public List<String> getList_line() {
            return list_line;
        }

        public void setList_line(List<String> list_line) {
            this.list_line = list_line;
        }

        String startTime, endTime;
        List<String> list_line;
    }

    private class SearchHistory {
        int Id;
        String transferStation;

        public int getId() {
            return Id;
        }

        public void setId(int id) {
            Id = id;
        }

        public String getTransferStation() {
            return transferStation;
        }

        public void setTransferStation(String transferStation) {
            this.transferStation = transferStation;
        }

        public SearchHistory(int id, String transferStation) {
            Id = id;
            this.transferStation = transferStation;
        }
    }

    @Override
    protected int getLayout() {
        return R.layout._zjh_layout_trafficontime;
    }
}
